package com.fxsh168.server.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.fxsh168.server.R;
import com.fxsh168.server.adapters.PassengerInformationAdapter;
import com.fxsh168.server.base.BaseActivity;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.entitys.PushOrdersEntity;
import com.fxsh168.server.entitys.RegiYZMCG;
import com.fxsh168.server.entitys.Sounds;
import com.fxsh168.server.maps.BNDemoGuideActivity;
import com.fxsh168.server.maps.NavQian;
import com.fxsh168.server.services.QueryDistanceService;
import com.fxsh168.server.utils.CircleImageView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import okhttp3.Call;

public class PushOrders extends BaseActivity implements AdapterView.OnItemClickListener {
    TextView teOver, teNext;
    private ListView mMapPassengerInfoListView;
    private List<PushOrdersEntity.DataBean> pushOrdersEntityDataBeanList;
    PassengerInformationAdapter passengerInfoAdapter;
    String mPhone, token, account;
    double mLatitude, mLongitude;
    private PushOrdersEntity pushOrdersEntity2;
    int CurPosition;
    PushOrdersEntity pushOrdersEntityAda;
    private boolean isDingDanJXCH;
    private AlertDialog dialogPu0, dialogPu1, dialogwl;
    private int length;
    PopupWindows_info popWindowInfo;
    PopupWindows_next popupWindows_next;
    LinearLayout mOrderParent;
    private int mPosition;
    String ids;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push_orders);
        //用eventbus接收传递过来的值
        SharedPreferences sp = getSharedPreferences(Constant.LOGINCLASS, MODE_PRIVATE);
        mPhone = sp.getString("mPhone", "");
        token = sp.getString("token", "");
        mOrderParent = (LinearLayout) findViewById(R.id.mOrderParent);
        mMapPassengerInfoListView = (ListView) findViewById(R.id.mapPassengerInformation);
        pushOrdersEntityDataBeanList = new ArrayList<>();     //创建数据源
        getData();   //创建适配器  先绑定数据源
        mMapPassengerInfoListView.setOnItemClickListener(this);
    }

    //    list的点击事件
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String statu = pushOrdersEntityDataBeanList.get(i).getStatus();
        String ids = pushOrdersEntityDataBeanList.get(i).getId();
        if (statu != null) {
            if (statu.equals("3")) {
                mPosition = i;
                popWindowInfo = new PopupWindows_info(PushOrders.this, mOrderParent, itemOnclick, i);
            } else if (statu.equals("6")) {
                mPosition = i;
                popupWindows_next = new PopupWindows_next(PushOrders.this, mOrderParent, itemOnclick, i);
            }
        } else {
            mPosition = i;
            popWindowInfo = new PopupWindows_info(PushOrders.this, mOrderParent, itemOnclick, i);
        }
    }


    //     pop上的点击事件
    private View.OnClickListener itemOnclick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            switch (id) {
                case R.id.mapPhone:       //拨打电话
                    initDialPhone(mPosition);
                    break;
                case R.id.mapRefuse:      //拒绝乘客
                    popWindowInfo.dismiss();
                    initRefuse();
                    break;
                case R.id.mJieChengKe:    //去接乘客
//                    popWindowInfo.dismiss();
                    initJieChengke(mPosition);
                    break;
                case R.id.teOver:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(PushOrders.this, QueryDistanceService.class);
                            intent.putExtra("ids", ids);
                            startService(intent);         //   乘客已经上车开始导航
                        }
                    }).start();
                    getSound();
                    break;
                case R.id.teNext:
                    Intent intent1 = new Intent(PushOrders.this, QueryDistanceService.class);
                    intent1.putExtra("ids", ids);
                    Intent intent3 = new Intent(PushOrders.this, NavQian.class);
                    intent3.putExtra("pushOrdersEntity2", pushOrdersEntity2);
                    Log.e("tag", "传输导航页面的数据" + pushOrdersEntity2);
                    intent3.putExtra("CurPosition", CurPosition);
                    intent3.putExtra("isDingDanJXCH", isDingDanJXCH);
                    intent3.setAction("btnRouteSchedul");
                    intent3.putExtra("biao", "hjc");
                    startActivity(intent3);
                    popupWindows_next.dismiss();
                    finish();
                    break;
            }
        }
    };


    //        乘客信息
    public class PopupWindows_info extends PopupWindow {
        View view;

        PopupWindows_info(Context mContext, View parent, View.OnClickListener onClickListener, int i) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.popwin_info, null);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            setBackgroundDrawable(new BitmapDrawable());
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            CircleImageView mapPortrait = (CircleImageView) view.findViewById(R.id.mapPortrait);
            TextView mJieChengKe = (TextView) view.findViewById(R.id.mJieChengKe);
            TextView mapRefuse = (TextView) view.findViewById(R.id.mapRefuse);
            TextView mapPhone = (TextView) view.findViewById(R.id.mapPhone);
            TextView mapEnd = (TextView) view.findViewById(R.id.mapEnd);
            TextView mapStart = (TextView) view.findViewById(R.id.mapStart);
            TextView mapNummberPeople = (TextView) view.findViewById(R.id.mapPeopleNum);
            TextView mapStartTime = (TextView) view.findViewById(R.id.mapStartTime);
            teOver = (TextView) view.findViewById(R.id.teOver);
            PushOrdersEntity.DataBean dataBean = pushOrdersEntity2.getData().get(i);
            mapEnd.setText(dataBean.getDown().toString().trim());
            mapStart.setText(dataBean.getAddresses().toString().trim());
            mapStartTime.setText(dataBean.getGotime().toString().trim());
            mapPhone.setText(dataBean.getAccount().toString());
            mapNummberPeople.setText(dataBean.getNumpeo().toString().trim());
            handlerTouch.sendEmptyMessageDelayed(0,3000);
            teOver.setOnClickListener(onClickListener);
            mapPhone.setOnClickListener(onClickListener);
            mapRefuse.setOnClickListener(onClickListener);
            mJieChengKe.setOnClickListener(onClickListener);
            mapPhone.setOnClickListener(onClickListener);
        }
    }

    Handler handlerTouch=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            teOver.setEnabled(true);
        }
    };


    //        乘客信息
    public class PopupWindows_next extends PopupWindow {
        View view;

        PopupWindows_next(Context mContext, View parent, View.OnClickListener onClickListener, int i) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.popwin_next, null);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            setBackgroundDrawable(new BitmapDrawable());
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            CircleImageView mapPortrait = (CircleImageView) view.findViewById(R.id.mapPortrait);
            TextView mapPhone = (TextView) view.findViewById(R.id.mapPhone);
            TextView mapEnd = (TextView) view.findViewById(R.id.mapEnd);
            TextView mapStart = (TextView) view.findViewById(R.id.mapStart);
            TextView mapNummberPeople = (TextView) view.findViewById(R.id.mapPeopleNum);
            TextView mapStartTime = (TextView) view.findViewById(R.id.mapStartTime);
            teNext = (TextView) view.findViewById(R.id.teNext);
            PushOrdersEntity.DataBean dataBean = pushOrdersEntity2.getData().get(i);
            mapEnd.setText(dataBean.getDown().toString().trim());
            mapStart.setText(dataBean.getAddresses().toString().trim());
            mapStartTime.setText(dataBean.getGotime().toString().trim());
            mapPhone.setText(dataBean.getAccount().toString());
            mapNummberPeople.setText(dataBean.getNumpeo().toString().trim());
            teNext.setOnClickListener(onClickListener);
            mapPhone.setOnClickListener(onClickListener);
        }
    }

    //获取数据源
    public List<PushOrdersEntity.DataBean> getData() {
        Intent intent = getIntent();
        mLatitude = intent.getDoubleExtra("mLatitude", 0.000000);
        mLongitude = intent.getDoubleExtra("mLongitude", 0.000000);
        isDingDanJXCH = intent.getBooleanExtra("isDingDanJX", false);
        pushOrdersEntity2 = (PushOrdersEntity) intent.getSerializableExtra("pushOrdersEntity");
        if (pushOrdersEntity2 != null && !TextUtils.isEmpty(pushOrdersEntity2.toString().trim())) {
            List<PushOrdersEntity.DataBean> data = pushOrdersEntity2.getData();
            ids = data.get(mPosition).getId().toString().trim();
            pushOrdersEntityDataBeanList.addAll(data);
            length = pushOrdersEntityDataBeanList.size();
            passengerInfoAdapter = new PassengerInformationAdapter(pushOrdersEntityDataBeanList, PushOrders.this);
            mMapPassengerInfoListView.setAdapter(passengerInfoAdapter);
            passengerInfoAdapter.notifyDataSetChanged();
        }
        return null;
    }

    //去接乘客
    private void initJieChengke(int i) {
        pushOrdersEntityAda = new PushOrdersEntity();
        pushOrdersEntityAda.setData(pushOrdersEntityDataBeanList);
        Intent intent = new Intent(PushOrders.this, NavQian.class);
        intent.putExtra("adalatitude", pushOrdersEntityDataBeanList.get(i).getLatitude().toString().trim());
        intent.putExtra("adalongitude", pushOrdersEntityDataBeanList.get(i).getLongitude().toString().trim());
        intent.putExtra("adalatitudel", pushOrdersEntityDataBeanList.get(i).getLatitudel().toString().trim());
        intent.putExtra("adalongitudel", pushOrdersEntityDataBeanList.get(i).getLongitudel().toString().trim());
        intent.putExtra("pushOrdersEntity", pushOrdersEntityAda);
        intent.putExtra("isDingDanJXCH", isDingDanJXCH);
        intent.putExtra("position", i);
        intent.setAction("PassAdapter");
        PushOrders.this.startActivity(intent);
    }


    //拒绝
    private void initRefuse() {
        if (pushOrdersEntityDataBeanList.size() > 0) {
            //自定义拒绝dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(PushOrders.this);
            View view1 = LayoutInflater.from(PushOrders.this).inflate(R.layout.jujuedialog_layout, null);
            builder.setView(view1);
            TextView cacel = (TextView) view1.findViewById(R.id.btnCacelP0);
            cacel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialogPu0.dismiss();
                }
            });
            TextView btnOk = (TextView) view1.findViewById(R.id.btnOKP0);
            btnOk.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    OkHttpUtils.post().addParams("id", ids).addParams("phone", mPhone)
                            .addParams("token", token).url(Constant.ORDERFUSEREQUESTPATH)
                            .build().execute(new StringCallback() {
                        @Override

                        public void onError(Call call, Exception e, int id) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(PushOrders.this);
                            View view1 = LayoutInflater.from(PushOrders.this).inflate(R.layout.wangluodialog_layout, null);
                            builder.setView(view1);
                            TextView btnOk = (TextView) view1.findViewById(R.id.btnOKfwq);
                            btnOk.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //让对话框消失
                                    dialogwl.dismiss();
                                }
                            });
                            dialogwl = builder.create();
                            dialogwl.setCanceledOnTouchOutside(false);
                            dialogwl.show();
                            WindowManager m = getWindowManager();
                            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                            WindowManager.LayoutParams p = dialogwl.getWindow().getAttributes(); // 获取对话框当前的参数值
                            p.height = (int) (d.getHeight() * 0.215); // 高度设置为屏幕的0.6
                            p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.95
                            dialogwl.getWindow().setBackgroundDrawableResource(R.drawable.shapedingdan);
                            dialogwl.getWindow().setAttributes(p);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            if (response != null) {
                                RegiYZMCG regiYZMCG = new Gson().fromJson(response, RegiYZMCG.class);
                                String code = regiYZMCG.getCode().trim();
                                if (code.equals(200 + "")) {
                                    length--;
                                    showToast("拒绝成功!");
                                    if (length == 0) {
                                        showToast("您已经拒绝全部订单!");
                                        PushOrders.this.finish();
                                    }
                                } else if (code.equals(203 + "")) {
                                    showToast("拒绝失败,请重新尝试！");
                                }
                            }
                        }
                    });
                    //让对话框消失
                    dialogPu0.dismiss();
                }
            });

            dialogPu0 = builder.create();
            dialogPu0.setCanceledOnTouchOutside(true);
            dialogPu0.show();
            WindowManager m = PushOrders.this.getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            WindowManager.LayoutParams p = dialogPu0.getWindow().getAttributes();  // 获取对话框当前的参数值
            p.height = (int) (d.getHeight() * 0.215); // 高度设置为屏幕的0.6
            p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.95
            dialogPu0.getWindow().setBackgroundDrawableResource(R.drawable.shapedingdan);
            dialogPu0.getWindow().setAttributes(p);
        }
    }

    //拨打电话
    private void initDialPhone(int diaPhoposition) {
        for (int i = 0; i < pushOrdersEntityDataBeanList.size(); i++) {
            if (diaPhoposition == i) {
                account = pushOrdersEntityDataBeanList.get(i).getAccount().toString().trim();
                if (!TextUtils.isEmpty(account)) {
                    //自定义拨打电话dialog
                    AlertDialog.Builder builder = new AlertDialog.Builder(PushOrders.this);
                    View view1 = LayoutInflater.from(PushOrders.this).inflate(R.layout.dialdialog_layout, null);
                    builder.setView(view1);
                    TextView cacel = (TextView) view1.findViewById(R.id.btnCacelP1);
                    cacel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialogPu1.dismiss();
                        }
                    });
                    TextView btnOk = (TextView) view1.findViewById(R.id.btnOKP1);
                    btnOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + account));
                            if (ActivityCompat.checkSelfPermission(PushOrders.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                showToast("权限被拒绝!");
                                return;
                            }
                            try {
                                PushOrders.this.startActivity(intent);
                            } catch (Exception e) {
                                showToast("权限被拒绝!");
                            }
                            //让对话框消失
                            dialogPu1.dismiss();
                        }
                    });
                    dialogPu1 = builder.create();
                    dialogPu1.setCanceledOnTouchOutside(true);
                    dialogPu1.show();
                    WindowManager m = PushOrders.this.getWindowManager();
                    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                    WindowManager.LayoutParams p = dialogPu1.getWindow().getAttributes(); // 获取对话框当前的参数值
                    p.height = (int) (d.getHeight() * 0.215); // 高度设置为屏幕的0.6
                    p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.95
                    dialogPu1.getWindow().setBackgroundDrawableResource(R.drawable.shapedingdan);
                    dialogPu1.getWindow().setAttributes(p);
                } else {
                    showToast("没电话号码!");
                }
            }
        }
    }

    //  获取语音文件
    public void getSound() {
        Log.e("tag", "获取语音文件  " + ids);
        OkHttpUtils.post().addParams("id", ids).url(Constant.SOUNDSPLAY).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Sounds sounds = new Gson().fromJson(response, Sounds.class);
                String code = sounds.getCode();
                if (code.equals(200 + "")) {
                    Log.e("tag", " 上车打印" + response);
                    //将获得的经纬度传递到导航页面
                    Intent intent3 = new Intent(PushOrders.this, NavQian.class);
                    intent3.putExtra("pushOrdersEntity2", pushOrdersEntity2);
                    Log.e("tag", "传输导航页面的数据" + pushOrdersEntity2);
                    intent3.putExtra("CurPosition", CurPosition);
                    intent3.putExtra("isDingDanJXCH", isDingDanJXCH);
                    intent3.setAction("btnRouteSchedul");
                    startActivity(intent3);
                    finish();
                } else if (code.equals(201 + "")) {
                    showToast("请求");
                }
            }
        });
    }


}
